<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="序列号">
        <el-input v-model="queryParams.serialNumber" placeholder="请输入序列号" clearable maxlength="50" />
      </el-form-item>
      <el-form-item label="打印机类型">
        <el-select v-model="queryParams.printerType" placeholder="请选择打印机类型" clearable>
          <el-option label="便携式打印机" value="便携式打印机" />
          <el-option label="高速打印机" value="高速打印机" />
        </el-select>
      </el-form-item>
      <el-form-item label="使用情况">
        <el-select v-model="queryParams.useStatus" placeholder="请选择使用情况" clearable>
          <el-option label="所有" value="" />
          <el-option
            v-for="dict in dict.type.use_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-download" @click="handleExport">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" @click="showImportDialog = true">导入</el-button>
      </el-col>
    </el-row>

    <!-- 导入弹窗 -->
    <el-dialog title="导入序列号" :visible.sync="showImportDialog" width="400px" append-to-body>
      <el-upload
        class="upload-demo"
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        accept=".xlsx,.xls"
        ref="upload"
      >
        <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件</div>
      </el-upload>
      <template #footer>
        <el-button @click="showImportDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmImport">确定导入</el-button>
      </template>
    </el-dialog>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="sequenceList"
      @selection-change="handleSelectionChange"
      border
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序列号" prop="serialNumber" align="center" />
      <el-table-column label="类型" prop="printerType" align="center" />
      <el-table-column label="使用情况" prop="useStatus" align="center">
        <template #default="scope">
          <el-tag
            :type="scope.row.useStatus === '0' ? 'danger' : 'success'"
          >
            {{ (dict.type.use_status.find(d => d.value === scope.row.useStatus) || {}).label || '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="打印机台数" prop="printCount" align="center" />
      <el-table-column label="创建者" prop="createBy" align="center" />
      <el-table-column label="创建时间" prop="createTime" align="center" />
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)" v-hasPermi="['nongjt:printSequence:edit']">编辑</el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            style="color: #f56c6c;"
            v-hasPermi="['nongjt:printSequence:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      layout="total, sizes, prev, pager, next, jumper"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="mt10">
        <el-form-item v-if="form.seqId" prop="seqId" hidden>
          <el-input v-model="form.seqId" />
        </el-form-item>
        <el-form-item label="序列号" prop="serialNumber">
          <el-input
            v-model="form.serialNumber"
            placeholder="请输入序列号"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="打印机类型" prop="printerType">
          <el-select v-model="form.printerType" placeholder="请选择打印机类型">
            <el-option label="便携式打印机" value="便携式打印机" />
            <el-option label="高速打印机" value="高速打印机" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用情况" prop="useStatus">
          <el-select v-model="form.useStatus" placeholder="请选择使用情况">
            <el-option
              v-for="dict in dict.type.use_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="form.createTime"
            type="date"
            placeholder="选择创建时间"
            value-format="yyyy-MM-dd"
            :disabled="form.seqId !== undefined"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listSequence, getSequence, addSequence, updateSequence, delSequence, exportSequence, importSequence, checkSerialUnique} from "@/api/njt/print/sequence";
import Dict from "@/views/system/dict/index.vue";

export default {
  components: { Dict },
  dicts: ["use_status"],
  data() {
    return {
      loading: true,
      sequenceList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serialNumber: "",
        printerType: "",
        useStatus: ""
      },
      selection: [],
      open: false,
      title: "",
      form: {},
      rules: {
        serialNumber: [
          { required: true, message: "请输入序列号", trigger: "blur" },
          {
            validator: async (rule, value, callback) => {
              if (!value) {
                return callback();
              }
              // 编辑时不校验当前记录的序列号
              if (this.form.seqId) {
                const originalData = await getSequence(this.form.seqId);
                if (originalData.data.serialNumber === value) {
                  return callback();
                }
              }
              try {
                const response = await checkSerialUnique(value);
                if (response.code !== 200) {
                  return callback(new Error(response.msg || "序列号已存在"));
                }
                callback();
              } catch (err) {
                callback(new Error("校验失败，请稍后重试"));
              }
            },
            trigger: "blur"
          }
        ],
        printerType: [{ required: true, message: "请选择打印机类型", trigger: "change" }],
        useStatus: [{ required: true, message: "请选择使用情况", trigger: "change" }],
        createTime: [{ required: true, message: "请选择创建时间", trigger: "change" }]
      },
      // 导入相关变量
      showImportDialog: false,
      fileList: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listSequence(this.queryParams).then(res => {
        this.sequenceList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      if (this.$refs.queryForm) {
        this.$refs.queryForm.resetFields();
      }
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        serialNumber: "",
        printerType: "",
        useStatus: ""
      };
      this.getList();
    },

    handleSelectionChange(selection) {
      this.selection = selection;
    },

    handleAdd() {
      this.open = true;
      this.title = "新增序列号";
      this.form = {
        createTime: new Date()
      };
    },

    handleEdit(row) {
      this.open = true;
      this.title = "编辑序列号";
      getSequence(row.seqId).then(res => {
        this.form = res.data;
        if (this.form.createTime) {
          this.form.createTime = new Date(this.form.createTime);
        }
      });
    },

    handleDelete(row) {
      this.$confirm(`确定删除序列号"${row.serialNumber}"?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delSequence(row.seqId).then(response => {
          if (response.code === 200) {
            this.$message.success("删除成功");
            this.getList();
          } else {
            this.$message.error(response.msg || "删除失败");
          }
        }).catch(err => {
          this.$message.error("删除失败：" + err.message);
        });
      });
    },

    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const action = this.form.seqId ? updateSequence : addSequence;
          action(this.form).then(response => {
            if (response.code === 200) {
              this.open = false;
              this.getList();
              this.$message.success("操作成功");
            } else {
              this.$message.error(response.msg || "操作失败");
            }
          }).catch(err => {
            this.$message.error("网络错误：" + err.message);
          });
        }
      });
    },

    // 批量导出
    handleExport() {
      this.$modal.loading("正在导出数据，请稍候...");
      exportSequence(this.queryParams).then(res => {
        this.$modal.closeLoading();
        // 处理响应：区分“Excel流”和“错误JSON”
        if (res.type === 'application/json') {
          // 若为JSON，说明后端返回错误
          const reader = new FileReader();
          reader.onload = () => {
            const errorInfo = JSON.parse(reader.result);
            this.$message.error(errorInfo.msg || "导出失败");
          };
          reader.readAsText(res);
        } else {
          // 若为Excel流，触发下载
          const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          const aLink = document.createElement('a');
          const url = window.URL.createObjectURL(blob);
          aLink.href = url;
          aLink.download = "打印序列号数据.xlsx";
          document.body.appendChild(aLink);
          aLink.click();
          document.body.removeChild(aLink);
          window.URL.revokeObjectURL(url);
        }
      }).catch(error => {
        this.$modal.closeLoading();
        this.$message.error("导出失败：" + (error.message || "网络异常"));
      });
    },

    // 导入文件选择
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },

    // 确认导入
    confirmImport() {
      if (this.fileList.length === 0) {
        this.$message.warning("请选择导入文件");
        return;
      }
      const formData = new FormData();
      formData.append('file', this.fileList[0].raw);

      importSequence(formData).then(response => {
        this.showImportDialog = false;
        this.fileList = [];
        this.$message.success(response.msg || "导入成功");
        this.getList();
      }).catch(err => {
        this.$message.error(`导入失败：${err.message || '未知错误'}`);
      });
    }
  }
};
</script>

<style scoped>
::v-deep .el-form-item__label {
  white-space: nowrap;
  display: inline-flex;
  align-items: center;
  padding-right: 10px;
}

::v-deep .el-dropdown-menu__item {
  padding: 8px 16px;
}

::v-deep .el-message-box__content {
  text-align: center;
  padding: 20px 15px;
}
</style>
